﻿using System;
using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using System.Data;

namespace msBsc.AppLogic.DataAlc
{
    public class CBizChatMessage : CustBizObject
    {
        private CDmDjkChatMessage m_CDmDjkChatMessage = new CDmDjkChatMessage();
        private CDmDjkChatMessage oDmDjkChatMessage
        {
            get { return m_CDmDjkChatMessage; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizChatMessage()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmDjkChatMessage.DJK_CHAT_MESSAGE);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["CHAT_MESSAGE_ID"];
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = this.DataObj.NewID();
            }
            return true;
        }

        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            }
            return true;
        }

        /// <summary>
        /// 消息发送
        /// </summary>
        /// <param name="senderId">发送人ID</param>
        /// <param name="senderNick">发送人呢称 可以为空</param>
        /// <param name="receiverId">接收人ID</param>
        /// <param name="receiverNick">接收人呢称 可以为空</param>
        /// <param name="message">消息内容</param>
        /// <param name="messageRmk">备注 可以为空</param>
        /// <param name="isNotice">是否公开 可选默认True 公开</param>
        /// <returns></returns>
        public string SendMessage(string senderId, string senderNick, string receiverId, string receiverNick, string message, string messageRmk, bool isNotice = true)
        {
            if (string.IsNullOrEmpty(senderId))
            {
                return "发送人不能为空。";
            }

            if (string.IsNullOrEmpty(receiverId))
            {
                return "接收人不能为空。";
            }
            if (string.IsNullOrEmpty(message))
            {
                return "聊天内容不能为空。";
            } if (string.IsNullOrEmpty(senderId))
            {
                return "接受人昵称不能为空。";
            }

            DataSet ds = new CDmDjkChatMessage();
            DataRow dr = ds.Tables[0].NewRow();
            dr["MESSAGE_SEND_TIME"] = this.dtCurrDateTime;
            dr["CHAT_MESSAGE_ID"] = this.DataObj.NewID();
            dr["IP_FOR_SENDER"] = msBsc.Cls.CommValiCollection.GetIp();
            dr["MESSAGE_IS_READ"] = 0;
            dr["MESSAGE_IS_NOTICE"] = isNotice;
            dr["MESSAGE_IS_DELETED"] = 0;

            dr["MESSAGE_SENDER_ID"] = senderId;
            dr["MESSAGE_SENDER_NICK"] = senderNick;
            dr["MESSAGE_RECEIVER_ID"] = receiverId;
            dr["MESSAGE_RECEIVER_NICK"] = receiverNick;
            dr["CONTENT_FOR_MESSAGE"] = message;
            dr["MESSAGE_RMK"] = messageRmk;

            ds.Tables[0].Rows.Add(dr);
            this.Update(ds);

            return "OK";
        }



        /// <summary>
        /// 获取所以 消息
        /// </summary>
        /// <param name="senderId">发送人ID</param>
        /// <param name="receiverId">接受人ＩＤ</param>
        /// <param name="isNotice">是否公开</param>
        /// <param name="IsRead">是否已读</param>
        /// <returns></returns>
        public DataSet GetAllSenderMessage(string senderId, string receiverId, string isNotice, string IsRead)
        {

            if (string.IsNullOrEmpty(senderId))
            {
                return null;
            }
            if (string.IsNullOrEmpty(receiverId))
            {
                return null;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("senderId", ParameterDirection.Input, EDbType.String, 36, senderId.Replace("'", "").Replace(",", "','")));
            parmCollection.Add(new CDbParm("receiverId", ParameterDirection.Input, EDbType.String, 36, receiverId.Replace("'", "").Replace(",", "','")));
            parmCollection.Add(new CDbParm("isNotice", ParameterDirection.Input, EDbType.String, 36, isNotice.Replace("'", "").Replace(",", "','")));
            parmCollection.Add(new CDbParm("IsRead", ParameterDirection.Input, EDbType.String, 36, IsRead.Replace("'", "").Replace(",", "','")));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT US.CUSTOMER_DEFAULT_PIC AS SENDER_PIC,US2.CUSTOMER_DEFAULT_PIC AS REGISTER_PIC,
MS.CHAT_MESSAGE_ID,MS.MESSAGE_SENDER_ID,MS.MESSAGE_RECEIVER_ID,MS.CONTENT_FOR_MESSAGE,
MS.MESSAGE_SEND_TIME,MS.MESSAGE_IS_READ,MS.MESSAGE_IS_NOTICE,
MS.MESSAGE_SENDER_NICK,MS.MESSAGE_RECEIVER_NICK,
MS.MESSAGE_IS_DELETED,MS.MESSAGE_RMK
FROM [dbo].[DJK_CHAT_MESSAGE] (NOLOCK) MS
LEFT JOIN [dbo].[DJK_CUSTOMER_REGISTER] (NOLOCK) US
ON MS.MESSAGE_SENDER_ID=US.CUSTOMER_REGISTER_ID 
LEFT JOIN [dbo].[DJK_CUSTOMER_REGISTER] (NOLOCK) US2 
ON MS.MESSAGE_RECEIVER_ID=US2.CUSTOMER_REGISTER_ID
	WHERE MS.MESSAGE_IS_DELETED=0  
	AND MS.MESSAGE_SENDER_ID=@senderId 
    AND MS.MESSAGE_RECEIVER_ID=@receiverId
	AND MS.MESSAGE_IS_NOTICE=@isNotice 
	AND MS.MESSAGE_IS_READ=@IsRead
	ORDER BY MS.MESSAGE_SEND_TIME ASC", parmCollection);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }


        /// <summary>
        /// 获取所以 消息
        /// </summary>
        /// <param name="receiverId">接受人ＩＤ</param>
        /// <param name="isNotice">是否公开</param>
        /// <param name="IsRead">是否已读</param>
        /// <returns></returns>
        public DataSet GetAllSenderMessage(string receiverId, string isNotice, string IsRead)
        {

            if (string.IsNullOrEmpty(receiverId))
            {
                return null;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("receiverId", ParameterDirection.Input, EDbType.String, 36, receiverId.Replace("'", "").Replace(",", "','")));
            parmCollection.Add(new CDbParm("isNotice", ParameterDirection.Input, EDbType.String, 36, isNotice.Replace("'", "").Replace(",", "','")));
            parmCollection.Add(new CDbParm("IsRead", ParameterDirection.Input, EDbType.String, 36, IsRead.Replace("'", "").Replace(",", "','")));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT US.CUSTOMER_DEFAULT_PIC AS SENDER_PIC,US2.CUSTOMER_DEFAULT_PIC AS REGISTER_PIC,
MS.CHAT_MESSAGE_ID,MS.MESSAGE_SENDER_ID,MS.MESSAGE_RECEIVER_ID,MS.CONTENT_FOR_MESSAGE,
MS.MESSAGE_SEND_TIME,MS.MESSAGE_IS_READ,MS.MESSAGE_IS_NOTICE,
MS.MESSAGE_SENDER_NICK,MS.MESSAGE_RECEIVER_NICK,
MS.MESSAGE_IS_DELETED,MS.MESSAGE_RMK
FROM [dbo].[DJK_CHAT_MESSAGE] (NOLOCK) MS
LEFT JOIN [dbo].[DJK_CUSTOMER_REGISTER] (NOLOCK) US
ON MS.MESSAGE_SENDER_ID=US.CUSTOMER_REGISTER_ID 
LEFT JOIN [dbo].[DJK_CUSTOMER_REGISTER] (NOLOCK) US2 
ON MS.MESSAGE_RECEIVER_ID=US2.CUSTOMER_REGISTER_ID
	WHERE MS.MESSAGE_IS_DELETED=0  
    AND MS.MESSAGE_RECEIVER_ID=@receiverId
	AND MS.MESSAGE_IS_NOTICE=@isNotice 
	AND MS.MESSAGE_IS_READ=@IsRead
	ORDER BY MS.MESSAGE_SEND_TIME ASC", parmCollection);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }


        /// <summary>
        /// 修改消息状态为已读
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public bool UpdateStatus(DataSet ds)
        {
            if (ds.Tables[0].Rows.Count <= 0)
            {
                return false;
            }
            if (ds.Tables[0].TableName != this.TableName)
            {
                ds.Tables[0].TableName = this.TableName;
            }
            foreach (DataRow item in ds.Tables[0].Rows)
            {
                item["MESSAGE_IS_READ"] = 1;
            }

            this.Update(ds);
            return true;
        }

        /// <summary>
        /// 获取当前用户 当前未读所有聊天信息
        /// </summary>
        /// <param name="receiverId">当前用户id</param>
        /// <returns></returns>
        public DataTable GetGroups(string receiverId)
        {
            if (string.IsNullOrEmpty(receiverId))
            {
                return null;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("receiverId", ParameterDirection.Input, EDbType.String, 36, receiverId.Replace("'", "").Replace(",", "','")));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT M.MESSAGE_SENDER_ID id,CUSTOMER_NICK name,CUSTOMER_DEFAULT_PIC face,M.msgCount
FROM [dbo].[DJK_CUSTOMER_REGISTER](NOLOCK) U
RIGHT JOIN (SELECT MESSAGE_SENDER_ID,COUNT(1) msgCount FROM  [dbo].[DJK_CHAT_MESSAGE] 
WHERE MESSAGE_RECEIVER_ID=@receiverId 
and MESSAGE_IS_READ=0
and MESSAGE_IS_NOTICE=0
GROUP BY MESSAGE_SENDER_ID) M
ON U.CUSTOMER_REGISTER_ID=M.MESSAGE_SENDER_ID", parmCollection);
            ds.Tables[0].TableName = this.TableName;
            return ds.Tables[0];

        }
        /// <summary>
        /// 获取最近 10 人聊天人
        /// </summary>
        /// <param name="receiverId"></param>
        /// <returns></returns>
        public DataTable GetChatRecently(string receiverId, int number = 10)
        {
            if (string.IsNullOrEmpty(receiverId))
            {
                return null;
            }
            if (number<10)
            {
                number = 10;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("receiverId", ParameterDirection.Input, EDbType.String, 36, receiverId.Replace("'", "").Replace(",", "','")));

            parmCollection.Add(new CDbParm("number", ParameterDirection.Input, EDbType.Integer,10,number));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT top (@number) M.MESSAGE_SENDER_ID id,CUSTOMER_NICK name,CUSTOMER_DEFAULT_PIC face,M.msgCount,M.MESSAGE_SEND_TIME 
FROM [dbo].[DJK_CUSTOMER_REGISTER](NOLOCK) U
RIGHT JOIN (select MESSAGE_SENDER_ID,0 msgCount,MAX(MESSAGE_SEND_TIME) MESSAGE_SEND_TIME from DJK_CHAT_MESSAGE
WHERE MESSAGE_RECEIVER_ID=@receiverId 
and (MESSAGE_IS_READ=0 OR MESSAGE_IS_READ=1) 
and MESSAGE_IS_NOTICE=0
group by MESSAGE_SENDER_ID) M
ON U.CUSTOMER_REGISTER_ID=M.MESSAGE_SENDER_ID

order by M.MESSAGE_SEND_TIME desc", parmCollection);
            DataTable dt = ds.Tables[0];
            dt.TableName = this.TableName;
            //int rowCount = dt.Rows.Count;
            //if (rowCount > number)
            //{
            //    DataTable tempdt = new DataTable();
            //    for (int i = (rowCount - 1); i >= (rowCount - number); i--)
            //    {
            //        tempdt.Rows.Add(dt.Rows[i]);
            //    }
            //    return tempdt;
            //}

            return dt;
        }

        /// <summary>
        /// 获取聊天记录
        /// </summary>
        /// <param name="senderId">发送人id</param>
        /// <param name="receiverId">接受人id</param>
        /// <param name="isNotice">是否公开</param>
        /// <param name="IsRead">是否已读</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageRows"></param>
        /// <returns></returns>
        public DataTable GetMessageRecord(string senderId, string receiverId, string isNotice, int pageIndex, int pageRows = 20)
        {
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("receiverId", ParameterDirection.Input, EDbType.String, 36, receiverId));
            parmCollection.Add(new CDbParm("senderId", ParameterDirection.Input, EDbType.String, 36, senderId));


            parmCollection.Add(new CDbParm("isNotice", ParameterDirection.Input, EDbType.String, 36, isNotice));
            parmCollection.Add(new CDbParm("pagerows", ParameterDirection.Input, EDbType.String, 36, pageRows));
            parmCollection.Add(new CDbParm("pagenum", ParameterDirection.Input, EDbType.String, 36, pageIndex));
            DataSet ds = this.DataObj.QueryBySP("DJK_SELECT_CHAT_MESSAGE_VIEW", parmCollection);

            return ds != null ? ds.Tables[0] : null;
        }

        protected override bool BeforeRowDeletedR(DataRow drw)
        {
            //using (msBsc.AppLogic.DataAlc.CBizShpPageColumn objtem = new CBizShpPageColumn())
            //{
            //    DataSet ds = objtem.SelectByPageNo(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //} 
            return true;
        }

        protected override bool AfterRowAdded(DataRow drw)
        {
            return true;
        }

        protected override bool AfterRowModified(DataRow drw)
        {
            return true;
        }

        protected override bool AfterRowDeletedR(DataRow drw)
        {
            return true;
        }


        public DataSet GetMessageCount(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return null;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("userId", ParameterDirection.Input, EDbType.String, 36, userId.Replace("'", "").Replace(",", "','")));
            DataSet ds = this.DataObj.QueryBySQL("select COUNT(MESSAGE_SENDER_ID) as MESSAGE_COUNT,MESSAGE_SENDER_ID from DJK_CHAT_MESSAGE where MESSAGE_RECEIVER_ID=@userId and MESSAGE_IS_READ=0 and MESSAGE_IS_DELETED=0 group by MESSAGE_SENDER_ID", parmCollection);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        //public DataSet SelectByIds(string strIdS)
        //{
        //    CDbParmCollection parmCollection = new CDbParmCollection();
        //    parmCollection.Add(new CDbParm("strIdS", ParameterDirection.Input, EDbType.String, 36, strIdS.Replace("'", "").Replace(",", "','")));
        //    DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE  " + this.KeyFieldName + " IN  ('@strIdS')");
        //    ds.Tables[0].TableName = this.TableName;
        //    return ds;
        //}
    }
}
